package com.dsr.service.impl;

import com.dsr.consts.PageResult;
import com.dsr.consts.Result;
import com.dsr.dao.RolesDao;
import com.dsr.entity.Roles;
import com.dsr.service.RolesService;
import com.dsr.util.IdWorker;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.List;

/**
 * (Roles)表服务实现类
 *
 * @author dsr
 * @since 2020-09-26
 */
@Service("rolesService")
public class RolesServiceImpl implements RolesService {
    @Autowired
    private RolesDao rolesDao;
    @Autowired
    private IdWorker idWorker;

    @Override
    public Result getEntity(String id) {
        Roles entity = rolesDao.selectByPrimaryKey(id);
        return Result.success(entity);
    }

    @Override
    public Result save(Roles roles) {
        roles.setId(String.valueOf(idWorker.nextId()));
        rolesDao.insertSelective(roles);
        return Result.success("保存成功");
    }

    @Override
    public Result update(Roles roles) {
        rolesDao.updateByPrimaryKeySelective(roles);
        return Result.success("修改成功");

    }

    @Override
    public Result delete(String id) {
        if (StringUtils.isNotEmpty(id)) {
            List<String> ids = Arrays.asList(id.split(","));
            Example example = new Example(Roles.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("id", ids);
            rolesDao.deleteByExample(example);
            return Result.success("删除成功");
        }
        return Result.error("请选择要删除的行");
    }

    @Override
    public Result query(int page, int size, Roles roles) {
        PageHelper.startPage(page, size);
        List<Roles> entityList = rolesDao.select(roles);
        PageInfo<Roles> pageInfo = new PageInfo<>(entityList);
        return Result.success(new PageResult<Roles>(pageInfo.getTotal(), pageInfo.getList()));
    }

    @Override
    public Result list() {
        return Result.success(rolesDao.selectAll());
    }
}